import { nextTick } from 'vue'
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import router from '@/router/index.js'
import { useUserStore } from '@/stores/modules/user.js'
import Stomp from 'stompjs'
import qs from 'qs'
let loading = null
// 存储请求的数组
const requests = []
const instance = axios.create({
  //production
  // baseURL: '/server',
  baseURL: import.meta.env.MODE == 'development' ? '' : '',
  timeout: 1000 * 60
})
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    config.headers['token'] = userStore.token || ''
    // 将请求存储到数组,需要时可以循环数组取消还未请求
    requests.push(config)
    return config
  },
  (error) => {
    console.log('%c接口地址：' + error.config.url + '%c ' + error.message || '无', 'padding: 3px; border-radius: 3px 0 0 3px; background:red;color:white;', 'padding: 3px; border-radius: 0 3px 3px 0; background:orange;color:white;')
    return Promise.reject(error)
  }
)
instance.interceptors.response.use(
  (response) => {
    if (response.data.message[0] == '["缺少token参数"]') {
      router.push({
        path: '/login'
      })
    }
    if (response.data.status == 200 || response.data.status == 300) {
      const config = response.config
      const index = requests.findIndex((item) => {
        if (item.url == config.url && JSON.stringify(item.params) == JSON.stringify(config.params)) {
          return item
        }
      })
      if (index != -1) {
        requests.splice(index, 1)
      }
      // console.log(requests)
      return response.data
    } else if (response.data.status == 700) {
      const userStore = useUserStore()
      userStore.clearUserInfor()
      router.push({
        path: '/login'
      })
      ElMessage({
        message: response.data.message[0],
        type: 'error',
        duration: 3 * 1000
      })
    } else {
      ElMessage({
        message: response.data.message[0],
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
      if (response.data.message[0] == '令牌已经失效') {
        const userStore = useUserStore()
        userStore.clearUserInfor()
        router.push({
          path: '/login'
        })
        location.reload()
      }
    }
  },
  (error) => {
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    console.log(error)
    return Promise.reject(error)
  }
)
const http = (url, method, params = {}, stringify = true, prefix = '', callback) => {
  if (method == 'get') {
    return instance({
      url: prefix + url,
      method: 'get',
      params: params
    })
  } else {
    return instance({
      url: prefix + url,
      method: 'post',
      data: stringify ? qs.stringify(params) : params,
      onUploadProgress: function (e) {
        // 上传进度
        if (callback) {
          e.loaded == e.total ? callback(100) : callback(Math.round((e.loaded / e.total) * 100))
        }
      }
    })
  }
}
const uploadFile = (url, formData, prefix = '', callback) => {
  return instance({
    url: prefix + url,
    method: 'post',
    data: formData,
    timeout: 1000 * 60 * 30, //上传超过30分钟超时,
    onUploadProgress: function (e) {
      if (callback) {
        e.loaded == e.total ? callback(100) : callback(Math.round((e.loaded / e.total) * 100))
      }
    }
  })
}
//下载文件
const downloadFile = (url, method, params) => {
  return instance({
    url,
    method,
    params,
    timeout: 1000 * 60 * 30, //下载超过30分钟超时
    responseType: 'blob' // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'  浏览器专属：'blob
  })
}
//table 点详情或编辑填充数据
const fillData = (target, origin) => {
  // 这里也可以根据id请求详情数据后再赋值
  // http('', 'get', { id: origin.id }).then(res=>{})
  nextTick(() => {
    for (const key in target) {
      if (Array.isArray(target[key])) {
        target[key] = origin[key].split(',') || []
      } else {
        target[key] = origin[key] || ''
      }
    }
  })
}
//合并对象数据
const mergeObj = (target, origin) => {
  for (let key in origin) {
    if (origin[key].constructor === Object) {
      if (target[key]) {
        mergeObj(target[key], origin[key])
      } else {
        target[key] = origin[key]
      }
    } else if (origin[key].constructor === Array) {
      target[key] = origin[key].slice()
      // if (!target[key]) {
      //   target[key] = origin[key].slice()
      // } else {
      //   origin[key].forEach((item) => {
      //     if (item.constructor === Object) {
      //       mergeObj()
      //     }
      //   })
      // }
    } else {
      target[key] = origin[key]
    }
  }
  return target
}
//获取嵌套数组第一个子元素的值
const getArrFirstData = (arr) => {
  let result = {}
  if (arr.length == 0) return result
  todo(arr)
  function todo(arr) {
    if (arr[0].children) {
      todo(arr[0].children)
    } else {
      result = arr[0]
    }
  }
  return result
}

export { http, uploadFile, downloadFile, fillData, mergeObj, getArrFirstData }
